import { Injectable } from '@angular/core';
import { select, Store } from '@ngrx/store';
import axios from 'axios';
import { AppState } from '../store/app.model';
import { getToken } from '../store/user/user.reducer';
//import { MessageService } from 'primeng/api';
const baseUrl = 'http://101.43.249.161:8080';
let token = '';
@Injectable()
export class RequestClass {
    //token:any = undefined;
    constructor(private store: Store<AppState>) {
        this.store.pipe(select(getToken)).subscribe((data) => {
            token = data;
        });
    }
    request = {
        async get(url, options?) {
            return this._normal('get', url, options, false);
        },
        async post(url, options) {
            return this._normal('post', url, options, false);
        },
        async put(url, options) {
            return this._normal('put', url, options, false);
        },
        async delete(url, options) {
            return this._normal('delete', url, options, false);
        },
        async Pget(url, options?) {
            return this._normal('get', url, options, true);
        },
        async Ppost(url, options) {
            return this._normal('post', url, options, true);
        },
        async Pput(url, options) {
            return this._normal('put', url, options, true);
        },
        async Pdelete(url, options) {
            return this._normal('delete', url, options, true);
        },
        async _normal(method, url, options, needPackage) {
            //console.log(token)
            const { headers, ...others } = options || {};
            let res;
            const mergeUrl =
                url.startsWith('http://') || url.startsWith('https://')
                    ? url
                    : baseUrl + url;
            try {
                res = await axios.request({
                    url: mergeUrl,
                    method,
                    headers: {
                        ...headers,
                        Authorization: token,
                    },
                    ...others,
                });
                if (!res.data) {
                    throw '返回数据格式异常';
                }
            } catch (e) {
                console.log('error', e);
                // const msg = '网络请求失败：网络请求错误'
                const msg = '尚无数据';
                return needPackage
                    ? undefined
                    : {
                          code: 404,
                          msg,
                      };
            }
            if (res.data.code != 200) {
                const msg = res.data.message;
                // const msg = '尚无数据'
            }
            return needPackage ? res.data.data : res.data;
        },
    };
}
